package com.github.byakkili.bim.protocol.json2protobuf.ws;

import cn.hutool.core.util.StrUtil;
import com.github.byakkili.bim.core.BimSession;
import com.github.byakkili.bim.core.handler.command.CommandFrame;
import com.github.byakkili.bim.core.support.util.BimSessionUtils;
import com.github.byakkili.bim.protocol.json2protobuf.BaseJson2protoBufCodec;
import com.github.byakkili.bim.protocol.ProtoBufHelper;
import com.google.protobuf.Message;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @author Guannian Li
 */
@Sharable
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WsJson2protoBufCodec extends BaseJson2protoBufCodec<TextWebSocketFrame> {
    /**
     * 单例
     */
    public static final WsJson2protoBufCodec INSTANCE = new WsJson2protoBufCodec();

    @Override
    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame textWsFrame, List<Object> out) {
        BimSession session = BimSessionUtils.get(ctx.channel());

        String text = textWsFrame.text();
        int startIndex = StrUtil.indexOf(text, '{');

        int command = Integer.parseInt(StrUtil.subPre(text, startIndex));
        String jsonStr = StrUtil.subSuf(text, startIndex);

        CommandFrame frame = convertCommandFrame(session, command, jsonStr);
        out.add(frame);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, CommandFrame<Message> frame, List<Object> out) {
        String jsonStr = ProtoBufHelper.serializeJson(frame.getMessage());

        TextWebSocketFrame textWsFrame = new TextWebSocketFrame(frame.getCommand() + jsonStr);
        out.add(textWsFrame);
    }
}
